﻿using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace BrnMall.Sdk.WeiXin.Tool
{
    public class RestHttp
    {
        public static T Get<T>(string url)
        {
            Trace.TraceInformation(url);

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            var response = (HttpWebResponse)request.GetResponse();
            var resStream = response.GetResponseStream();
            if (resStream == null) return default(T);
            var wwwresult = new StreamReader(resStream).ReadToEnd();
            Trace.TraceInformation(wwwresult);
            return JsonConvert.DeserializeObject<T>(wwwresult);
        }

        public static T Post<T>(string url, string data)
        {
            Trace.TraceInformation(url);
            Trace.TraceInformation(data);
            var request = (HttpWebRequest)WebRequest.Create(url);
            var postData = Encoding.UTF8.GetBytes(data);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(postData, 0, postData.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            var resStream = response.GetResponseStream();
            if (resStream == null) return default(T);
            var wwwresult = new StreamReader(resStream).ReadToEnd();
            Trace.TraceInformation(wwwresult);
            return JsonConvert.DeserializeObject<T>(wwwresult);
        }
        public static string Post(string url, string data)
        {
            Trace.TraceInformation(url);
            Trace.TraceInformation(data);
            var request = (HttpWebRequest)WebRequest.Create(url);
            var postData = Encoding.UTF8.GetBytes(data);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(postData, 0, postData.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            var resStream = response.GetResponseStream();
            if (resStream == null) return string.Empty;
            var wwwresult = new StreamReader(resStream).ReadToEnd();
            Trace.TraceInformation(wwwresult);
            return wwwresult;
        }
    }
}
